import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/dio/PostDio.dart';
import 'package:wayofdressing/dio/configureDio.dart';

import '../components/passagemodule.dart';
import '../good_method/decode_base64_to_bytes.dart';

class OwnScreen extends StatefulWidget {
  static final String id = 'ownscrenn';

  @override
  State<OwnScreen> createState() => _OwnScreenState();
}

class _OwnScreenState extends State<OwnScreen> {
  String name = '';

  ImageProvider headImage = AssetImage('images/peanut.jpg');

  String account = '';

  int followingCount = 0;

  int followersCount = 0;

  List<Widget> posts = [];
  ImageProvider postImage = AssetImage('images/peanut.jpg');
  int id = 0;

  Future<void> getInfo() async {
    final Map<String, dynamic>? args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    setState(() {
      id = args?['id'] ?? 0; // 获取 receiverId
      headImage = args?['headImage'] ?? AssetImage('images/peanut.jpg');
      name = args?['name'] ?? '';
    });
    _loadPostsById();
  }

  Future _loadPostsById() async {
    try {
      Response response = await getPostsByUserId(userId: id, dio: dio);
      dynamic data = response.data['data'];
      List<Widget> loadingPosts = [];
      for (dynamic item in data) {
        String title = item['title'];
        String content = item['content'];
        int sharesCount = item['sharesCount'];
        int likesCount = item['likesCount'];
        int commentsCount = item['commentsCount'];
        int favoritesCount = item['favoritesCount'];
        String? base64Image = item['imageBytes'];
        if (base64Image != null && base64Image.isNotEmpty) {
          Uint8List imageBytes = decodeBase64ToBytes(base64Image);
          postImage = MemoryImage(imageBytes);
        }
        Map<String, dynamic> postInfo = {
          'title': title,
          'content': content,
          'likesCount': likesCount,
          'sharesCount': sharesCount,
          'commentsCount': commentsCount,
          'favoritesCount': favoritesCount,
          'authorName': name,
          'authorId': id,
        };
        loadingPosts.add(CreatePostWidget(postInfo));
      }
      setState(() {
        posts = loadingPosts;
      });
    } on Exception catch (e) {
      print(e);
    }
  }

  Widget CreatePostWidget(Map<String, dynamic> postInfo) {
    return PassageModule(
      image: postImage,
      headImage: headImage,
      postInfo: postInfo,
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    getInfo(); // 在这里安全调用，但确保只调用一次
  }

  @override
  Widget build(BuildContext context) {
    MenuController menuController = MenuController();
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 200,
        actions: [
          MenuAnchor(
            controller: menuController,
            menuChildren: [
              InMenuButton(
                onPressed: () {
                  menuController.close();
                },
                text: '关于我们',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '背景设置',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '联系客服',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '问题咨询',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: Alignment(-3, 0.5),
              padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: Icon(
                  Icons.keyboard_control_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 30),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Row(
                    children: [
                      Row(
                        children: [
                          CircleAvatar(
                            backgroundImage: headImage,
                            radius: 32,
                          )
                        ],
                      ),
                      SizedBox(
                        width: 30,
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '$name',
                            style: TextStyle(fontSize: 28),
                          ),
                        ],
                      )
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Column(
                        children: [
                          Text(
                            '关注',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 12,
                            ),
                          ),
                          Text(
                            '$followingCount',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 12,
                            ),
                          )
                        ],
                      ),
                      Column(
                        children: [
                          Text(
                            '粉丝',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 12,
                            ),
                          ),
                          Text(
                            '$followersCount',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 12,
                            ),
                          )
                        ],
                      ),
                      Container(
                        height: 40,
                        child: TextButton(
                          style: ButtonStyle(
                              shape: MaterialStateProperty.all(
                                  RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(25))),
                              backgroundColor:
                                  MaterialStateProperty.all(Colors.redAccent)),
                          child: Text(
                            '关注',
                            style: TextStyle(color: Colors.white, fontSize: 16),
                          ),
                          onPressed: () {},
                        ),
                      ),
                      Container(
                          width: 40,
                          decoration: BoxDecoration(
                              color: Colors.black.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(15),
                              border:
                                  Border.all(color: Colors.black, width: 2)),
                          child: Icon(Icons.chat_bubble_outline_rounded))
                    ],
                  )
                ],
              ),
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      // 阴影颜色和透明度
                      spreadRadius: 2,
                      // 阴影扩展半径
                      blurRadius: 5,
                      // 阴影模糊半径
                      offset: Offset(0, 5), // 阴影偏移量
                    ),
                  ],
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(25),
                      topRight: Radius.circular(25))),
              child: Column(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                          topRight: Radius.circular(25),
                          topLeft: Radius.circular(25)),
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1), // 阴影颜色
                          offset: Offset(0, 1), // 阴影偏移（横向和纵向）
                          blurRadius: 1.0, // 模糊半径
                          spreadRadius: 1.0, // 扩展半径（可控制阴影的扩展程度）
                        ),
                      ],
                    ),
                    margin: EdgeInsets.only(bottom: 8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '帖子',
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                  Expanded(
                    child: posts.length != 0
                        ? GridView.builder(
                            itemCount: posts.length,
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              mainAxisSpacing: 8,
                              childAspectRatio: 1 / 1.5,
                            ),
                            itemBuilder: (BuildContext context, index) =>
                                posts[index],
                          )
                        : Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              SizedBox(height: 150,),
                              Icon(
                                Icons.article_outlined,
                                size: 80,
                              ),
                              Text('TA还没有发布作品!')
                            ],
                          ),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
